package cool.xinya.ess.service.impl;

import cool.xinya.ess.dao.TSysUserMapper;
import cool.xinya.ess.entity.TSysUser;
import cool.xinya.ess.security.ShiroUser;
import cool.xinya.ess.service.UserService;
import cool.xinya.ess.util.DateUtil;
import cool.xinya.ess.util.SessionUtil;
import cool.xinya.ess.vo.LoginVo;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.security.crypto.password.StandardPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

@Service
@Transactional
public class UserServiceImpl implements UserService {
    @Resource
    private TSysUserMapper userMapper;
    @Resource
    private StandardPasswordEncoder encoder;

    @Override
    public ShiroUser login(LoginVo loginVo) {
        String loginName = loginVo.getLoginName();
        String password = loginVo.getPassword();
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(loginName, password);
        subject.login(token);
        // 封装个人信息
        ShiroUser shiroUser = (ShiroUser) subject.getPrincipal();
        Session session = subject.getSession();
        shiroUser.setSessionId(session.getId().toString());
        subject.runAs(subject.getPrincipals());
        return shiroUser;
    }

    @Override
    public void addUser(TSysUser user) {
        user.setPassword(encoder.encode(user.getPassword()));
        String creator = SessionUtil.getLoginName();
        user.setCreateBy(creator);

        Date time = DateUtil.getCurrentTime();
        user.setCreateTime(time);
        user.setLatestModifyTime(time);
        user.setIsPki((byte) 0);

        // 设置过期时间为2999年
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String dateStr = "2999-06-01 00:00:00";
        Date date = null;
        try {
            date = simpleDateFormat.parse(dateStr);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        user.setExpireTime(date);
        userMapper.insertSelective(user);
    }
}
